package com.example.service.impl;

import com.alibaba.fastjson.JSON;
import com.example.entity.Position;
import com.example.repository.PositionRepository;
import com.example.service.PositionService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.bulk.BackoffPolicy;
import org.elasticsearch.action.bulk.BulkProcessor;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.ByteSizeUnit;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;

@Service
@Slf4j
public class PositionServiceImpl implements PositionService {
    @Autowired
    private PositionRepository repository;

    @Autowired
    private RestHighLevelClient client;

    private static final String POSITION_INDEX = "position2";

    @Override
    public List<Position> getAll() {
        return repository.findAll();
    }

    @Override
    public List<Map<String, Object>> searchPos(String keyword,String fieldName, int pageNo, int pageSize) throws IOException {
        if (pageNo < 1) {
            pageNo = 1;
        }
        SearchRequest request = new SearchRequest(POSITION_INDEX);
        SearchSourceBuilder builder = new SearchSourceBuilder();

        builder.from((pageNo - 1) * pageSize);
        builder.size(pageSize);

        MatchQueryBuilder queryBuilder = QueryBuilders.matchQuery(fieldName, keyword);
        builder.query(queryBuilder);
        builder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        request.source(builder);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        List<Map<String, Object>> list = new ArrayList<>();

        SearchHit[] hits = response.getHits().getHits();
        for (SearchHit hit : hits) {
            list.add(hit.getSourceAsMap());
        }
        return list;
    }

    @Override
    public void importAll() {
        importToEsFromMySQL();
    }

    private void importToEsFromMySQL() {
        BulkProcessor bulkProcessor = getBulkProcessor(client);
        try{
            // 此处可用根据分页,每次查询3000条做一次批量提交
            final List<Position> positions = repository.findAll();
            for (Position position : positions) {
                log.info("============="+position.getPositionName()+"=================");
                final Map map = JSON.parseObject(JSON.toJSONString(position), Map.class);
                bulkProcessor.add(new IndexRequest(POSITION_INDEX).source(map));
            }
            bulkProcessor.flush();
        } catch (Exception e){
            log.info(e.getMessage());
        } finally {
            log.info("execution final");
        }
    }

    private BulkProcessor getBulkProcessor(RestHighLevelClient client) {
        BulkProcessor bulkProcessor = null;
        try {
            BulkProcessor.Listener listener = new BulkProcessor.Listener() {
                @Override
                public void beforeBulk(long executionId, BulkRequest request) {
                    log.info("Try to insert data number : " + request.numberOfActions());
                }

                @Override
                public void afterBulk(long executionId, BulkRequest request, BulkResponse response) {
                    log.info("************** Success insert data number : " + request.numberOfActions() + " , id: " + executionId);
                }

                @Override
                public void afterBulk(long executionId, BulkRequest request, Throwable failure) {
                    log.error("Bulk is unsuccess : " + failure + ", executionId: " + executionId);
                }
            };
            BiConsumer<BulkRequest, ActionListener<BulkResponse>> bulkConsumer = (request, bulkListener) -> client.bulkAsync(request, RequestOptions.DEFAULT, bulkListener);
            BulkProcessor.Builder builder = BulkProcessor.builder(bulkConsumer, listener);
            builder.setBulkActions(5000);
            builder.setBulkSize(new ByteSizeValue(100L, ByteSizeUnit.MB));
            builder.setConcurrentRequests(10);
            builder.setFlushInterval(TimeValue.timeValueSeconds(100L));
            builder.setBackoffPolicy(BackoffPolicy.constantBackoff(TimeValue.timeValueSeconds(1L), 3));
            bulkProcessor = builder.build();
        } catch (Exception e) {
            e.printStackTrace();
            try {
                bulkProcessor.awaitClose(100L, TimeUnit.SECONDS);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
        return bulkProcessor;
    }
}
